#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "mp3_player.h"
#include "mp3dec.h"
#include "util.h"

#define PCM_OUTPUT_BUF_SIZE       (1152 * 2)    /* short */
#define PCM_PLAY_BUF_SIZE         (1152 * 2)    /* short */
#define VOLATILE_FIFO_DEEPSIZE    (10)


typedef volatile struct fifo_t vfifo_t;
struct fifo_t
{
    uint32_t samrateFIFO[VOLATILE_FIFO_DEEPSIZE];
    uint32_t positionFIFO[VOLATILE_FIFO_DEEPSIZE];
    int cnt;
    int cur_index;
};

typedef struct hmp3_t hmp3_t;
struct hmp3_t
{
    FIL filestream;
    volatile unsigned char *row_data_cur_ptr;
    vfifo_t samrateFIFO;
};

hmp3_t *hmp3;

int MP3Player_init()
{
    int res = mp3_decode_stream_init();
    if (res)
    {
        return res;
    }

    return 0;
}

static int load_file(const TCHAR *path)
{
    FRESULT fr = f_open(&hmp3->filestream, path, FA_OPEN_EXISTING | FA_READ);
    if (fr != FR_OK)
    {
        return -1;
    }
    start_a_dma_aligned();
    return 0;
}

volatile int res;
/**
  * @brief 加载文件，初始化MP3文件流
  */
int MP3Player_PlayFile(const TCHAR *path)
{
    FRESULT fr = f_open(&hmp3->filestream, path, FA_OPEN_EXISTING | FA_READ);
    if (fr != FR_OK)
    {
        return -1;
    }

    ID3V2 id;
    uint32_t br;
    f_read(&hmp3->filestream, &id, sizeof(id), &br);
    if (strncmp(id.header, "ID3", 3))
    {
        return -1;
    }

    char *Size = &id.size[0];
    int tagHeadSize = (Size[0]&0x7F)*0x200000+ (Size[1]&0x7F)*0x400 + (Size[2]&0x7F)*0x80 +(Size[3]&0x7F);
    f_lseek(&hmp3->filestream, tagHeadSize);

/********************************************************************/

    bsp_flag_led_off();
    while (1)
    {
        bsp_flag_led_on();
        bsp_flag_led_off();
        TIMx_mdelay(10);

        bsp_flag_led_on();
        HAL_DMA_Start(&hDataDma, (uint32_t)hmp3->outputpcm, (uint32_t)hmp3->outputpcm, 1024);
        HAL_DMA_PollForTransfer(&hDataDma, HAL_DMA_FULL_TRANSFER, 1000);
        bsp_flag_led_off();


        TIMx_mdelay(500);
    }

    /********************************************************************/


    start_a_dma_aligned();

    HAL_TIM_Base_Start(&hmp3SampleTim);

    return 0;
}

/**
 * @brief 下一首
 */
static void next()
{

}

/**
 * @brief 播放指定歌曲
 */
static void playIndex(int index)
{

}

/**
 * @brief 暂停或继续
 */
static void pause(int index)
{

}